//
//  HJHomeController.m
//  newOcWeibo
//
//  Created by heJing on 15/7/20.
//  Copyright (c) 2015年 heima. All rights reserved.
//

#import "HJHomeController.h"
#import "HJHomeButton.h"
#import "HJMenuContentController.h"
#import "HJPopMenuView.h"
#import "HJAccount.h"
#import "AFNetworking.h"
#import "SVProgressHUD.h"
#import "UIImageView+WebCache.h"
#import "HJStatus.h"
#import "HJTableCell.h"

@interface HJHomeController ()
@property(nonatomic, weak)HJHomeButton *titleBtn;

///  存储所有微博数据
@property (nonatomic, strong) NSArray *statuses;

// 缓存cell的高度
// 1.线程安全2.内存紧张会自动释放 3.不会拷贝key
@property (nonatomic, strong) NSCache *rowHeigthCache;

@end

UIWindow *_window;
@implementation HJHomeController


- (void)viewDidLoad {
    [super viewDidLoad];
    
  // 1. 设置导航条
    [self setNavBar];
    
    // 2.初始化默认界面
    if (self.defaultCenterView) {
        self.defaultCenterView.iconImageName = @"visitordiscover_feed_image_house";
        self.defaultCenterView.infoStr = @"当你关注一些人以后，他们发布的最新消息会显示在这里";
        self.defaultCenterView.show = YES;
    }else{
        // 1.获取用户信息
        [self setupUserInfo];
        
        // 2.获取微博数据
        [self setupLoadStatuses];

    }
}


- (void)setupUserInfo
{
    // 1.封装请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    HJAccount *account = [HJAccount accountFromSandbox];
    parameters[@"access_token"] = account.access_token;
    parameters[@"uid"] = account.uid;
    // 2.获取网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 3.发送请求
    [manager GET:@"https://api.weibo.com/2/users/show.json" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
        HJLog(@"%@", responseObject);

        // 判断用户头像是否已经更新
        NSString *new = responseObject[@"profile_image_url"];
        if ([account.profile_image_url isEqualToString:new]) {
            return ;
        }
        
        // 只有头像不相同, 才需要更新和保存
        account.profile_image_url = responseObject[@"profile_image_url"];
        [account save];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [SVProgressHUD showWithStatus:@"获取用户信息失败"];
    }];
}


// 获取微博数据
- (void)setupLoadStatuses{
    // 1.封装请求参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"access_token"] = [HJAccount accountFromSandbox].access_token;
//    parameters[@"count"] = @(5);
    
    // 2.获取网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 3.发送请求
    [manager GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {

        // 3.1取出微博数据
        NSArray *dictArr = responseObject[@"statuses"];
       
        self.statuses = [HJStatus objectArrayWithKeyValuesArray:dictArr];
        
        // 3.1取出微博数据
//        self.statuses = responseObject[@"statuses"];
        
        [self.statuses writeToFile:@"/Users/hejing/Desktop/abc.plist" atomically:YES];
        
        // 3.2刷新表格
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"获取微博数据失败"];
        [SVProgressHUD dismiss];
    }];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    // 开始旋转
//    HJDefaultCenterView *dcView = self.view;
//    [dcView startRotate];
    [self.defaultCenterView startRotate];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    HJDefaultCenterView *dcView = self.view;
//    [dcView stopRotate];
    [self.defaultCenterView stopRotate];
}


-(void)setNavBar
{
    // 1. 左边leftBarButtonItem
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithNorImage:@"navigationbar_friendsearch" higImage:@"navigationbar_friendsearch_highlighted" title:nil target:nil action:nil];
    
    // 2. 右边
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithNorImage:@"navigationbar_pop" higImage:@"navigationbar_pop_highlighted" title:nil target:self action:@selector(scan)];
    
    // 3.设置中间标题
    HJHomeButton *titleBtn = [[HJHomeButton alloc]init];
    [titleBtn setTitle:@"王八蛋" forState:UIControlStateNormal];
    [titleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    // 默认状态图片
    [titleBtn setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    // 选中状态图片
    [titleBtn setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateSelected];
    // 不要调整高亮
    titleBtn.adjustsImageWhenHighlighted = NO;
    
    [titleBtn sizeToFit]; // 设置之后会自动调整里面的子控件
    [titleBtn addTarget:self action:@selector(titleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.titleView = titleBtn;
    
    self.titleBtn = titleBtn;

}

-(void)titleBtnClick:(HJHomeButton *)homeBtn
{
    homeBtn.selected = !homeBtn.selected;

    // 2.显示菜单
//    [self showMenuView];
    
    // 3.菜单内容控制器
    HJMenuContentController *hcVc = [[HJMenuContentController alloc] init];
    hcVc.view.size = CGSizeMake(150, 200);
 
    // 4. 菜单内容视图
    [HJPopMenuView popFrom:homeBtn contentController:hcVc dismiss:^{
        // 回调玩之后执行
        homeBtn.selected = !homeBtn.selected;
    }];
    
}

/** 显示菜单
-(void)showMenuView
{
    UITableView *tb = [[UITableView alloc] init];
    tb.size = CGSizeMake(150, 200);
    tb.x = 10;
    tb.y = 15;

    
    // 2.创建菜单
    UIImageView *menuView = [[UIImageView alloc] init];
    menuView.image = [UIImage imageNamed:@"popover_background"];
    menuView.userInteractionEnabled = YES;
    // 3.设置菜单的frame
    CGFloat menuViewY = 64-10;
    CGFloat menuViewW = CGRectGetMaxX(tb.frame) + tb.x;;
    CGFloat menuViewH = CGRectGetMaxY(tb.frame) + tb.y;
    CGFloat menuViewX = self.view.frame.size.width * 0.5 - menuViewW * 0.5;
    menuView.frame = CGRectMake(menuViewX, menuViewY, menuViewW, menuViewH);
    [menuView addSubview:tb];
    
    // 4.创建一个蒙版
    UIButton *cover = [[UIButton alloc] init];
    cover.frame = [UIScreen mainScreen].bounds;
    cover.backgroundColor = [UIColor clearColor];
    [cover addTarget:self action:@selector(coverClick:) forControlEvents:UIControlEventTouchUpInside];
    // 5.将菜单添加到蒙版上
    [cover addSubview:menuView];

    // 6. 设置window， 将蒙版添加到window上面
    _window = [[UIWindow alloc] init];
    _window.frame = [UIScreen mainScreen].bounds;
    _window.hidden = NO;
    _window.windowLevel = MAXFLOAT;
    _window.backgroundColor = [UIColor clearColor];
    [_window addSubview:cover];

}
*/

-(void)coverClick:(UIButton *)cover
{
    _window = nil;
    // 切换箭头
    self.titleBtn.selected = !self.titleBtn.selected;

}

- (void)scan
{
    
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"HJScanController" bundle:nil];
    
    UIViewController *scanVc = sb.instantiateInitialViewController;
    
    [self presentViewController:scanVc animated:YES completion:nil];
}


#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.statuses.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.创建cell
    HJTableCell *cell = [tableView dequeueReusableCellWithIdentifier:[HJTableCell identifier]];

    // 2.设置数据
    /*
    HJStatus *status = self.statuses[indexPath.row];
    HJUser *user = status.user;
    cell.textLabel.text = user.name;
//    cell.detailTextLabel.text = status.source; // 来源
    cell.detailTextLabel.text = status.created_at; // 创建时间
    NSURL *url = [NSURL URLWithString:user.profile_image_url];
    [cell.imageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"iOS8"]];
    */
    
    //2.2设置数据
    HJStatus *status = self.statuses[indexPath.row];
    cell.status = status;
    
    // 3.返回cell
    return cell;
}

// 2
// 只要有一行cell进入视野范围内就会调用
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.取出对应行的模型
    HJStatus *status = self.statuses[indexPath.row];
    
    // 2.先从缓存中获取高度, 没有才计算
    NSNumber *rowHeight = [self.rowHeigthCache objectForKey:status.idstr];
    CGFloat cellHeight = [rowHeight doubleValue];
    if (rowHeight == nil) {

        // 2.取出cell
        HJTableCell *cell = [tableView dequeueReusableCellWithIdentifier:[HJTableCell identifier]];
        // 3.获取高度
        /*
         1.搞一个模型存储每一行的高度
         2.搞一个属性(NSDictionary)
         */
        cellHeight = [cell cellHeightWithStatus:status];
        
        // 4.缓存每一行的高度
        [self.rowHeigthCache setObject:@(cellHeight) forKey:status.idstr];
    }
    
    // 4.设置高度
    return cellHeight;
}

// 预估每一行cell的高度, 可以提高性能
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 因为是预估，所以设置的没有太大含义
    return 200;
}

#pragma mark - lazy
- (NSCache *)rowHeigthCache
{
    if (!_rowHeigthCache) {
        _rowHeigthCache = [[NSCache alloc] init];
    }
    
    return _rowHeigthCache;
}




@end
